/**
 * 
 */
package com.edocbase.desktop.swt.widgets;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.ArrayUtils;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
/**
 * @author X61
 * 
 */
public class RunBrowserFunction extends BrowserFunction {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
		.getLogger(RunBrowserFunction.class);	
	RunBrowserFunction(Browser browser) {
		super(browser, "run");
	}

	@Override
	public Object function(Object[] arguments) {
		super.function(arguments);
		if (logger.isDebugEnabled()) {
			logger.debug("" + ArrayUtils.toString(arguments));
		}
		
		if (arguments.length >=2){
			String name = arguments[0].toString();
			String method = arguments[1].toString();
			Object[] paras = new Object[0];
			Class<?>[] paraTypes = new Class<?>[0];
			if (arguments.length > 2){
				int len = arguments.length - 2;
				paras = new Object[len];
				for (int start=2;start < arguments.length;start++){
					paras[start-2] = arguments[start];
				}
			}
			paraTypes = new Class<?>[paras.length];
			for (int i=0;i<paras.length;i++){
				paraTypes[i] = paras[i].getClass();
			}
			Object fun = FunctionRegister.getRegister().getFunction(name);
			try {
				if (fun == null){
					return null;
				}
				
				Method m = fun.getClass().getMethod(method, paraTypes);
				if (m != null){
					Object result = m.invoke(fun, paras);
					return result;
				}
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
